import { CategoryTree, ECategory } from "@/views/type";
import { defineStore } from "pinia";
import { ref } from "vue";

import { useApi } from "@/api";
import { Tool } from "@/utils/tool";
const api = useApi();

//仓库就是处理数据

const useCategory = defineStore("ecategory", () => {
  // 1.获取分类
  const eCategory = ref<ECategory[]>([]);
  //2.转化为树形分类
  const categoryTree = ref<CategoryTree[]>([]);
  // 3.分类的映射id和名称
  const categoryMap = new Map<number, string>();

  //服务器端返回的分类数组 为其赋值
  async function getECategory() {
    // 1.获取分类
    eCategory.value = await api.getCategoryAll<ECategory[]>();
    //2.把分类的id和对应的name存到 map中
    eCategory.value.forEach((item:ECategory)=>{
      categoryMap.set(item.id!,item.name)
    })

    //2.转化为树形分类
    categoryTree.value = Tool.array2Tree(eCategory.value, 0);
  }

  return {
    eCategory,
    categoryTree,
    categoryMap,
    getECategory,
  };
},{persist:true});

export default useCategory;
